<template>
  <div>
    <!--面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--        卡片区域-->
    <el-card>
      <!--  添加按钮-->
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="openAddRole">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表-->
      <el-table v-loading="loading"
                :data="roleList"
                border
                stripe
      >
        //展示权限
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!--                       <pre> {{scope.row.children}}</pre>-->
            <el-row v-for="(item1,i1) in scope.row.children"
                    :key="item1.id" :class="['bdbottom',i1===0? 'bdtop': '','vcenter']"
            >
              <!--渲染一级权限-->
              <el-col :span="5">
                <el-tag>{{ item1.name }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--渲染二级权限-->
              <el-col :span="19">
                <el-row v-for="(item2,i2) in item1.children"
                        :key="item2.id" :class="[i2===0?'bdtop':'','vcenter']"
                >
                  <el-col :span="6">
                    <el-tag type="success">{{ item2.name }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag v-for="(item3,i3) in item2.children" :key="item3.id" closable
                            type="warning" @close="removeMenuById(scope.row.id,item3.id)"
                    >
                      {{ item3.name }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>

          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="nameZh"></el-table-column>
        <el-table-column label="角色描述" prop="remark"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <!--修改-->
            <el-button   v-hasRole="['admin']" icon="el-icon-edit" size="mini" type="primary"
                       @click="openEditRole(scope.row)"
            >修改
            </el-button>
            <!--删除-->
            <el-button   v-hasRole="['admin']" icon="el-icon-delete" size="mini" type="danger"
                       @click="deleteRole(scope.row.id)"
            >删除
            </el-button>
            <!--分配权限-->
            <el-tooltip   v-hasRole="['admin']" :enterable="false" content="分配权限" effect="dark" placement="top">
              <el-button icon="el-icon-setting" size="mini" type="warning"
                         @click="openAssPow(scope.row)"
              >分配权限
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>

      </el-table>
      <!-- 添加对话框-->
      <el-dialog
        :visible.sync="addRoleDialog"
        title="添加角色"
        width="40%"
        @close="addDialogClosed"
      >
        <!--内容主体区域-->
        <el-form ref="addRoleRef" :model="addRole" :rules="addRoleRules" label-width="90px">
          <el-form-item label="英文名称" prop="name">
            <el-input v-model="addRole.name"></el-input>
          </el-form-item>
          <el-form-item label="角色名称" prop="nameZh">
            <el-input v-model="addRole.nameZh"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="remark">
            <el-input v-model="addRole.remark"></el-input>
          </el-form-item>
        </el-form>
        <!--内容底部区域-->
        <span slot="footer" class="dialog-footer">
                <el-button @click="addRoleDialog = false">取 消</el-button>
                <el-button type="primary" @click="addRoleYes">确 定</el-button>
                </span>

      </el-dialog>
      <!-- 修改对话框-->
      <el-dialog
        :visible.sync="editRoleDialog"
        title="修改用户"
        width="50%"
      >
        <el-form ref="editRoleRef" :model="editRole" :rules="addRoleRules" label-width="80px">
          <el-form-item label="角色">
            <el-input v-model="editRole.name" disabled></el-input>
          </el-form-item>
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="editRole.nameZh"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="editRole.remark"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
               <el-button @click="editRoleDialog = false">取 消</el-button>
                <el-button type="primary" @click="editRoleYes">确 定</el-button>
                </span>

      </el-dialog>
      <!--分配权限对话框-->
      <el-drawer
        :visible.sync="assPowDialog"
        title="分配权限"
      >
        <div class="demo-drawer__content">


          <el-tree
            ref="treeRef"
            :data="menuTree"
            :default-checked-keys="defKes"
            :props="menuTreeProps"
            default-expand-all
            node-key="id"
            show-checkbox
          >
          </el-tree>

          <div class="demo-drawer__footer">
            <el-button style="position: absolute; right: 20px" @click="assPowDialog = false">取 消</el-button>
            <el-button style="position: absolute; right: 100px" type="primary" @click="assPowYes">确 定</el-button>
          </div>
        </div>

      </el-drawer>
    </el-card>
  </div>
</template>

<script>
import { Message, MessageBox } from 'element-ui'
import { addRolePost, assPow, deletePow, deleteRole, editRole, powList, roleList } from '../../api/boot/api'

export default {
  name: 'RoleList',
  data() {
    return {
      queryInfo: {
        query: ''
      },
      roleList: [],
      loading: false,
      //添加对话框
      addRoleDialog: false,
      //修改对话框
      editRoleDialog: false,
      //添加数据
      addRole: {
        name: '',
        nameZh: '',
        remark: ''
      },
      addRoleRules: {
        name: [{ required: true, message: '请填写角色英文名称', trigger: 'blur' }],
        nameZh: [{ required: true, message: '请填写角色中文名称', trigger: 'blur' }]
      },
      editRole: {
        id: 4,
        name: '',
        nameZh: '',
        remark: ''
      },
      assPowDialog: false,
      menuTree: [],
      menuTreeProps: {
        label: 'name',
        children: 'children'
      },
      defKes: [],
      powData: {
        roleId: '',
        mids: ''
      }
    }
  },
  methods: {

    async getRoleList() {
      this.loading = true
      roleList().then((res) => {
        for (let i = 0; i < res.obj.length; i++) {
          res.obj[i].children = []
        }
        for (let i = 0; i < res.obj.length; i++) {
          res.obj[i].children = this.list_to_tree(res.obj[i].menus)
        }

        this.roleList = res.obj
        this.loading = false
      })

    },
    //打开编辑角色对话框
    openEditRole(roleInfo) {
      this.editRoleDialog = true
      this.editRole = roleInfo
      // console.log(roleInfo)
    },
    deleteRole(roleId) {
      MessageBox.confirm('此操作将永久删除角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        deleteRole('/staff/deleteRole/' + roleId).then(res=>{
          if (res) {

            this.getRoleList()
          }
        })
        // const res = await this.$http.delete('/staff/deleteRole/' + roleId)
        // if (res) {
        //   this.getRoleList()
        // }
      }).catch(() => {
        Message({
          type: 'info',
          message: '已取消删除'
        })

      })

    },
    addDialogClosed() {
      this.$refs.addRoleRef.resetFields()
    },
    //打开编辑角色对话框
    openAddRole() {
      this.addRoleDialog = true
    },
    addRoleYes() {
      this.$refs.addRoleRef.validate(async valid => {
        if (!valid) return
        addRolePost( this.addRole).then(res=>{
          if (res) {
            this.addRoleDialog = false
            this.getRoleList()
          }
        })
        // const res = await this.$http.post('/staff/addRole',)

      })
    },
    editRoleYes() {
      this.$refs.editRoleRef.validate(async valid => {
        if (!valid) return
        editRole(this.editRole).then((res) => {
          if (res) {
            this.editRoleDialog = false
            this.getRoleList()
          }
        })
        // const res = await this.$http.put('/staff/editRole', )

      })
    },
    //打开分配权限对话框
    async openAssPow(menuInfo) {
      this.powData.roleId = menuInfo.id
      this.assPowDialog = true
      powList(this.queryInfo).then((res) => {
        if (!res) return
        //获取到的数据
        this.menuTree = this.list_to_tree(res.obj)
        this.defKes = this.getDdfKes(menuInfo.menus)
      })

    },
    getDdfKes(list) {
      const arr = []
      for (let i = 0; i < list.length; i++) {
        if (list[i].level === 2) {
          arr.push(list[i].id)
        }
      }
      return arr
    },
    //根据id删除权限
    removeMenuById(rid, mid) {
      MessageBox.confirm('删除后用户将不再享有该权限，是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        deletePow('/staff/deletePow/' + rid + '/' + mid).then((res) => {
          if (res) {
            this.getRoleList()
          }
        })
        // const res = await this.$http.delete()

      }).catch(() => {
        Message({
          type: 'info',
          message: '已取消删除'
        })

      })
    },
    //分配权限
    async assPowYes() {
      this.loading = true
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const keyStr = keys.join(',')
      this.powData.mids = keyStr

      assPow(this.powData).then((res) => {
        if (res) {
          this.assPowDialog = false
          this.loading = false
          this.getRoleList()
        }
      })

    },
    //list列表转换成tree
    list_to_tree(list) {
      const map = []
      const roots = []
      for (let i = 0; i < list.length; i++) {
        map[list[i].id] = i
        list[i].children = []
        // console.log(list[i].children)
      }
      for (let i = 0; i < list.length; i++) {
        const node = list[i]
        console.log(node.parentId)
        if (node.parentId === 1) {
          roots.push(node)
        } else {
          if (node.parentId != null) {
            list[map[node.parentId]].children.push(node)
          }
        }
      }
      return roots
    }

  },
  created() {
    this.getRoleList()
  }

}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
